import React from 'react';
import {Button, Icon, Tree, Checkbox, Spin, message} from 'antd';
import {WeaTools, WeaDialog, WeaSearchGroup, WeaFormItem, WeaInput, WeaSelect, WeaHelpfulTip,WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import * as lodash from 'lodash';
import EOrderCol from './base/EOrderCol'
import EField_New from './base/EField_New'
const TreeNode = Tree.TreeNode;

// 流程中心，数据来源
class Content_8_DataSource extends React.Component {
    constructor(props) {
        super(props);
        this.getButtons = this.getButtons.bind(this);
        this.getTreeData = this.getTreeData.bind(this);
        this.getTreeNodes = this.getTreeNodes.bind(this);
        this.onLoadData = this.onLoadData.bind(this);
        this.onExpand = this.onExpand.bind(this);
        this.onCheck = this.onCheck.bind(this);
        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);

        const {tabNew = {}, tabData = {}} = props;

        const {workflowSource = {}} = tabData;
        const {typeids, flowids, nodeids} = workflowSource;

        const wftypeCheckedKeys = typeids ? typeids.split(',').map(item => 'wftype_' + item) : [];
        const wfCheckedKeys = flowids ? flowids.split(',').map(item => 'wf_' + item) : [];
        const nodeCheckedKeys = nodeids ? nodeids.split(',').map(item => 'node_' + item) : [];

        const viewType = tabData.viewType || tabNew.viewType.selected;
        const isShowNodeBtn = viewType == '1' || viewType == '2' || viewType == '4';  // 待办、已办和我的请求显示是否开启节点按钮
        const hasNodeData = !!nodeids;

        this.state = {
            visible: true,
            id: tabData.id,
            title: tabData.title || '',
            viewType: viewType,
            isComplete: tabData.isComplete || tabNew.isComplete.selected,
            showCopy: tabData.showCopy,
            showCount: tabData.showCount,
            isArrangement: tabData.isArrangement,
            orderColVisible: false,
            eFieldNewVisible: false,
            orderColDataSource: lodash.isEmpty(tabData.orderColDataSource) ? tabNew.orderColDataSource : tabData.orderColDataSource,
            orderColUsedKeys: tabData.orderColUsedKeys || [],
            showTimeout: tabData.showTimeout,
            isExclude: tabData.isExclude || tabNew.isExclude.selected,
            workflowSource: workflowSource,
            treeLoading: false,
            treeData: [],
            checkedKeys: {checked: [...wftypeCheckedKeys, ...wfCheckedKeys, ...nodeCheckedKeys], halfChecked: []},
            expandedKeys: wftypeCheckedKeys,
            isShowNodeBtn: isShowNodeBtn,
            isNeedNode: hasNodeData,
            hasNodeData: hasNodeData,
            eFieldNewDataSource: tabData.eFieldNewDataSource || tabNew.eFieldNewDataSource,
            eFieldNewUsedKeys: tabData.eFieldNewUsedKeys || [],
            scrollDirection: tabData.scrollDirection || tabNew.scrollDirection.selected,
        };
    }
    componentWillMount() {
        const {isExclude, isShowNodeBtn, hasNodeData} = this.state;
        if (isExclude != '2') { // 选择或排除选择
            this.getTreeData(isShowNodeBtn && hasNodeData);
        }
    }

    render() {
        const {tabNew} = this.props;
        const {
            visible, title, viewType, isComplete, showCopy, isArrangement, showCount,
            orderColVisible, eFieldNewVisible, orderColDataSource, orderColUsedKeys, showTimeout,
            isExclude, treeLoading, treeData, checkedKeys, expandedKeys, isShowNodeBtn, isNeedNode, hasNodeData,
            eFieldNewDataSource, eFieldNewUsedKeys,scrollDirection
        } = this.state;

        let orderColComp = <div></div>;
        if (orderColVisible) {
            const orderColProps = {
                orderColDataSource: _.cloneDeep(orderColDataSource),
                orderColUsedKeys: _.cloneDeep(orderColUsedKeys),
                onOk: (data) => {
                    this.setState({
                        orderColDataSource: data.orderColDataSource,
                        orderColUsedKeys: data.orderColUsedKeys,
                        orderColVisible: false
                    });
                },
                onCancel: () => {
                    this.setState({
                        orderColVisible: false
                    });
                }
            };
            orderColComp = <EOrderCol {...orderColProps}/>
        }
        let EFieldNew = <div></div>;
        if (eFieldNewVisible) {
            const eFieldNewProps = {
                eFieldNewDataSource: _.cloneDeep(eFieldNewDataSource),
                eFieldNewUsedKeys: _.cloneDeep(eFieldNewUsedKeys),
                onOk: (data) => {
                    this.setState({
                        eFieldNewDataSource: _.cloneDeep(data.eFieldNewDataSource),
                        eFieldNewUsedKeys: _.cloneDeep(data.eFieldNewUsedKeys),
                        eFieldNewVisible: false
                    });
                },
                onCancel: () => {
                    this.setState({
                        eFieldNewVisible: false
                    });
                }
            };
            EFieldNew = <EField_New {...eFieldNewProps}/>
        }

        const orderColUsedNames = [];
        for (let i = 0, len = orderColUsedKeys.length; i < len; i++) {
            for (let j = 0, len2 = orderColDataSource.length; j < len2; j++) {
                if (orderColUsedKeys[i] == orderColDataSource[j].key) {
                    orderColUsedNames.push(orderColDataSource[j].fieldName + '-' + (orderColDataSource[j].orderType == '0' ? getLabel(340,"降序") : getLabel(339,"升序")));
                }
            }
        }
        
        const eFieldNewUsedNames = [];
        for (let i = 0; i < eFieldNewUsedKeys.length; i++) {
            for (let j = 0 ; j < eFieldNewDataSource.length; j++) {
                if (eFieldNewUsedKeys[i] == eFieldNewDataSource[j].key) {
                    eFieldNewUsedNames.push(eFieldNewDataSource[j].name);
                }
            }
        }

        let orderTitles ="";
        for(let i = 0;i < orderColUsedNames.length; i++){
            orderTitles = orderTitles + orderColUsedNames[i];
        }

        let eFieldTitles ="";
        for(let i = 0;i < eFieldNewUsedNames.length; i++){
            eFieldTitles = eFieldTitles + eFieldNewUsedNames[i];
        }


        return (
            <WeaDialog
                className="portal-esetting-dialog"
                visible={visible}
                title={getLabel(19480, '内容设置')}
                icon="icon-coms-portal"
                iconBgcolor='#1a57a0'
                style={{width: 700}}
                resize={true}
                hasScroll={true}
                buttons={this.getButtons()}
                onCancel={this.onCancel}
            >
                <WeaSearchGroup title={getLabel(33396, '设置项')} needTigger={true} showGroup={true}>
                    <WeaFormItem label={getLabel(24986, '标题')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                        <WeaInput inputType="multilang" isBase64={true} value={title} viewAttr={3} onChange={value => this.setState({title: value})}/>
                    </WeaFormItem>
                    <WeaFormItem label={getLabel(17483, '查看类型')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                        <div style={{width: '100%'}}>
                            <WeaSelect
                                options={
                                    tabNew.viewType.options.map((item) => {
                                        return {key: item.key, selected: false, showname: item.value};
                                    })
                                }
                                value={viewType}
                                onChange={value => {
                                    const isShowNodeBtn = (value == '1' || value == '2' || value == '4');
                                    this.getTreeData(isShowNodeBtn && hasNodeData);
                                    this.setState({viewType: value, isShowNodeBtn: isShowNodeBtn});
                                }}
                            />
                        </div>
                        {
                            viewType =='6'|| viewType=='7'||viewType=='8'?
                                <div style={{height: '0px', marginTop: '10px'}}>
                                </div> :
                        <div style={{height: '30px', marginTop: '10px'}}>
                            {
                                viewType == '4' ?
                                    <div style={{display: 'inline-block', width: '100px', marginRight: '10px'}}>
                                        <WeaSelect
                                            options={
                                                tabNew.isComplete.options.map((item) => {
                                                    return {key: item.key, selected: false, showname: item.value};
                                                })
                                            }
                                            style={{width: '120px'}}
                                            value={isComplete}
                                            onChange={value => this.setState({isComplete: value})}
                                        />
                                    </div>
                                    : ''
                            }
                            {viewType == '1' ?
                                <Checkbox checked={showCopy}    style={{ "top": "3px",position: "relative","width": "110px", overflow:" hidden","-webkit-line-clamp": "1", "text-overflow": 'ellipsis', "display": 'inline-block', "white-space":" nowrap"}} onChange={e => this.setState({showCopy: e.target.checked})}><span title={getLabel(386553, '显示抄送事宜')}>{getLabel(386553, '显示抄送事宜')}</span></Checkbox> : ''
                            }
                            {viewType == '2' ?
                                <Checkbox checked={isArrangement}   style={{ "top": "3px",position: "relative","width": "110px", overflow:" hidden","-webkit-line-clamp": "1", "text-overflow": 'ellipsis', "display": 'inline-block', "white-space":" nowrap"}} onChange={e => this.setState({isArrangement: e.target.checked})}><span title={getLabel(386554, '显示办结事宜')}>{getLabel(386554, '显示办结事宜')}</span></Checkbox> : ''
                            }
                            {viewType == '1' || viewType == '2' || viewType == '3' || viewType == '4' || viewType == '5' || viewType == '10' ?
                                <Checkbox checked={showCount}   style={{ "top": "3px",position: "relative","width": "110px", overflow:" hidden","-webkit-line-clamp": "1", "text-overflow": 'ellipsis', "display": 'inline-block', "white-space":" nowrap"}} onChange={e => this.setState({showCount: e.target.checked})}><span title={getLabel(82641, '显示未读数')}>{getLabel(82641, '显示未读数')}</span></Checkbox> : ''
                            }
                            {viewType == '1' ?
                                <Checkbox checked={showTimeout}  style={{ "position": "relative","width": "110px", "-webkit-line-clamp": "1", "display": 'inline-block', "white-space":" nowrap"}} onChange={e => this.setState({showTimeout: e.target.checked})}>
                                    <span style={{marginRight: '5px'}} title={getLabel(126834, '优先显示超时流程')}>{getLabel(126834, '优先显示超时流程')}</span>
                                    <WeaHelpfulTip title={getLabel(386555, '启用后，将优先显示超时流程，再按设置的排序字段排序。')}/>
                                </Checkbox> : ''
                            }
                        </div>
                        }
                    </WeaFormItem>
                    <WeaFormItem label={getLabel(19495, '显示字段')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                        {EFieldNew}
                        <div style={{height: '30px', lineHeight: '23px'}}>
                            <i className="icon-coms-Flow-setting portal-esetting-btn" style={{position:"relative","z-index":"12"}} onClick={() => this.setState({eFieldNewVisible: true})}/>
                            <span title={eFieldTitles} style={{position: "absolute", overflow:" hidden","-webkit-line-clamp": "2", "text-overflow": 'ellipsis', display: '-webkit-box', "-webkit-box-orient": 'vertical',top: '0px'}}>&nbsp;&nbsp;&nbsp;&nbsp;{eFieldNewUsedNames.join('，')}</span>
                        </div>
                    </WeaFormItem>

                    <WeaFormItem label={getLabel(15512, '排序字段')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                        {orderColComp}
                        <div style={{height: '30px', lineHeight: '30px'}}>
                            <i className="icon-coms-Flow-setting portal-esetting-btn"  style={{position:"relative","z-index":"12"}} onClick={() => this.setState({orderColVisible: true})}/>
                            <span  title={orderTitles} style={{position: "absolute", overflow:" hidden","-webkit-line-clamp": "1", "text-overflow": 'ellipsis', display: '-webkit-box', "-webkit-box-orient": 'vertical',top: '0px'}}>&nbsp;&nbsp;&nbsp;&nbsp;{orderColUsedNames.join('，')}</span>
                        </div>
                    </WeaFormItem>
                    <WeaFormItem label={getLabel(20281, '滚动方向')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                        <div style={{width: '100px'}}>
                            <WeaSelect
                                options={
                                    tabNew.scrollDirection.options.map((item) => {
                                        return {key: item.key, selected: false, showname: item.value};
                                    })
                                }
                                value={scrollDirection}
                                onChange={value => {
                                    this.setState({scrollDirection: value});
                                }}
                            />
                        </div>
                    </WeaFormItem>
                    <WeaFormItem label={getLabel(21672, '流程来源')} labelCol={{span: 6}} wrapperCol={{span: 16}}>
                        <div style={{width: '100%'}}>
                            <WeaSelect
                                options={
                                    tabNew.isExclude.options.map((item) => {
                                        return {key: item.key, selected: false, showname: item.value};
                                    })
                                }
                                value={isExclude}
                                onChange={value => {
                                    this.setState({isExclude: value});
                                    if (value != '2') {
                                        this.getTreeData(isShowNodeBtn && hasNodeData);
                                    }
                                }}
                            />
                        </div>
                        {
                            isExclude != '2' ?
                                <Spin spinning={treeLoading}>
                                    <div style={{width: '465px', height: '300px', overflow: 'auto'}}>
                                        <div style={{display: isShowNodeBtn ? 'block' : 'none', position: 'absolute', top: '10px', right: '20px'}}>
                                            <Button size="small" title={isNeedNode ? getLabel(386556, '包含节点') : getLabel(386557, '不包含节点')} onClick={() => this.getTreeData(!isNeedNode)}>
                                                <i className={isNeedNode ? 'icon-coms-DisplaySubordinates' : 'icon-coms-NoDisplayOfSubordinates'}/>
                                            </Button>
                                        </div>
                                        <Tree
                                            checkable={true}
                                            checkStrictly={true}
                                            expandedKeys={expandedKeys}
                                            checkedKeys={checkedKeys}
                                            onExpand={this.onExpand}
                                            loadData={this.onLoadData}
                                            onCheck={this.onCheck}
                                        >
                                            {this.getTreeNodes(treeData)}
                                        </Tree>
                                    </div>
                                </Spin>
                                : ''
                        }
                    </WeaFormItem>
                </WeaSearchGroup>
            </WeaDialog>
        );
    }

    getButtons() {
        let buttons = [];
        buttons.push(<Button type="primary" onClick={this.onOk}>{getLabel(826, '确定')}</Button>);
        buttons.push(<Button type="ghost" onClick={this.onCancel}>{getLabel(31129, '取消')}</Button>);
        return buttons;
    }

    getTreeData(isNeedNode) {
        const { viewType } = this.state;
        this.setState({treeLoading: true, isNeedNode: isNeedNode});

        WeaTools.callApi('/api/public/browser/data/-99991', 'GET', {
            isWfTree: 1,
            needNode: isNeedNode ? 1 : 0,
            containsOfs: 1,
            viewType: viewType
        }).then(data => {
            this.setState({treeLoading: false, treeData: data.datas.subs});

            if (isNeedNode) {
                const {workflowSource} = this.state;
                const {flowids} = workflowSource;
                const flowidarr = flowids.split(',');
                if (flowidarr && flowidarr.length) {
                    for (let i = 0, len = flowidarr.length; i < len; i++) {
                        this.onLoadData({props: {id: flowidarr[i]}}, true);
                    }
                }
            }
        });
    }

    getTreeNodes(treeData) {
        const loop = (data, pids) => {
            return data.map((item) => {
                const _pids = _.cloneDeep(pids);
                _pids.push(item.type + '_' + item.id);

                const children = item.subs;
                if (children && children.length) {
                    return <TreeNode key={item.type + '_' + item.id} id={item.id} pids={_pids} title={item.name} isLeaf={!item.isParent}>{loop(children, _pids)}</TreeNode>;
                } else {
                    return <TreeNode key={item.type + '_' + item.id} id={item.id} pids={_pids} title={item.name} isLeaf={!item.isParent}/>;
                }
            });
        };

        return loop(treeData, []);
    }

    onLoadData(node, isInit) {
        const {id} = node.props;

        if (!isInit) {
            this.setState({treeLoading: true});
        }

        WeaTools.callApi('/api/public/browser/data/-99991', 'GET', {
            isWfTree: 1,
            needNode: 1,
            type: 'wf',
            id: id
        }).then(data => {
            const loop = (treeData, pid, data) => {
                for (let i = 0, len = treeData.length; i < len; i++) {
                    if (treeData[i].id == pid && treeData[i].type == 'wf') {
                        treeData[i].subs = data || [];
                        break;
                    } else {
                        const children = treeData[i].subs;
                        if (children && children.length) {
                            loop(children, pid, data);
                        }
                    }
                }
            };

            const {treeData, expandedKeys} = this.state;
            loop(treeData, id, data.datas);
            this.setState({treeLoading: false, treeData: treeData, expandedKeys: [...expandedKeys, 'wf_' + id]});
        });
    }

    onExpand(expandedKeys) {
        this.setState({expandedKeys: expandedKeys});
    }

    onCheck(checkedKeys, e) {
        const {eventKey, pids, children} = e.node.props;
        const { isExclude } = this.state;
        const childrenKeys = this.getChildrenKeys(children || []);

        let checked = [];
        if (e.checked) {
            checked = _.concat(checkedKeys.checked, ...childrenKeys);
            // if(isExclude === '0'){
            //     checked = _.concat(checkedKeys.checked, ...childrenKeys);
            // }else{
            //     checked = _.concat(checkedKeys.checked, ...pids, ...childrenKeys);
            // }
        } else {

            checked = _.pullAll(checkedKeys.checked, _.concat(...pids, childrenKeys));
        }
        const _checked = _.uniq(checked);

        const {isShowNodeBtn, isNeedNode} = this.state;

        let typeids = '', flowids = '', nodeids = '';
        for (let i = 0, len = _checked.length; i < len; i++) {
            const _keys = _checked[i].split('_');
            if (_keys[0] == 'wftype') {
                typeids += _keys[1] + ',';
            } else if (_keys[0] == 'wf') {
                flowids += _keys[1] + ',';
            } else if (isShowNodeBtn && isNeedNode && _keys[0] == 'node') {
                nodeids += _keys[1] + ',';
            }
        }

        this.setState({checkedKeys: {checked: _checked, halfChecked: []}, workflowSource: {typeids, flowids, nodeids}});
    }

    getChildrenKeys(children) {
        const keys = [];
        for (let i = 0, len = children.length; i < len; i++) {
            const {key, props} = children[i];

            keys.push(key);
            if (props.children) {
                const keys = this.getChildrenKeys(props.children);
                keys.push(...keys);
            }
        }
        return keys;
    }

    onOk() {
        if (!this.state.title) {
            message.warning(getLabel(15859, '必要信息不完整！'));
        } else {
            const {orderColDataSource:ds, orderColUsedKeys:keys} = this.state;

            const orderColUsed = [];
            for (let i = 0, len = keys.length; i < len; i++) {
                for (let j = 0, len2 = ds.length; j < len2; j++) {
                    if (keys[i] == ds[j].key) {
                        orderColUsed.push(ds[j]);
                    }
                }
            }

            const {workflowSource, isShowNodeBtn, isNeedNode} = this.state;
            let {typeids, flowids, nodeids} = workflowSource;
            nodeids = (isShowNodeBtn && isNeedNode) ? nodeids : '';

            this.props.onOk({...this.state, orderColUsed, workflowSource: {typeids, flowids, nodeids}});
        }
    }

    onCancel() {
        this.props.onCancel();
    }
}

export default Content_8_DataSource;
